<template>
  <view class="authentication">
    <Navbar :title="t('auth.title')"> </Navbar>
    <view class="container">
      <view class="content">
        <view class="upload">
          <view class="upload-img" @click="upload(1)">
            <img
              :src="
                cardImgFront1 ? cardImgFront1 : '../../static/my/upload.png'
              "
              alt=""
            />
          </view>
        </view>
        <view class="title">
          <view class="text1">{{ t("auth.front") }}</view>
          <view class="text2" v-if="!hasauthen ">{{ t("auth.uploadf") }}</view>
        </view>
      </view>
      <view class="content">
        <view class="upload">
          <view class="upload-img" @click="upload(2)">
            <img
              :src="cardImgBack1 ? cardImgBack1 : '../../static/my/upload.png'"
              alt=""
            />
          </view>
        </view>
        <view class="title">
          <view class="text1">{{ t("auth.opposite") }}</view>
          <view class="text2" v-if="!hasauthen ">{{ t("auth.uploado") }}</view>
        </view>
      </view>
      <view class="content2">
        <view v-if="!hasauthen">
          <view class="title">{{ t("auth.plpi") }}</view>
          <view class="name">{{ t("auth.email") }}</view>
          <view class="item-input">
            <input
              type="text"
              v-model="email"
              :placeholder="t('auth.Plemail')"
            />
          </view>
          <view class="email">
            <view class="email-input">
              <input
                type="text"
                v-model="verfyCode"
                :placeholder="t('auth.plcode')"
              />
            </view>
            <button class="code-btn" @click="sendCode">
              {{ send ? t("auth.code") : t("auth.code") }}
            </button>
          </view>
        </view>
        <view class="name">{{ t("auth.name") }}</view>
        <view class="item-input">
          <input
            type="text"
            v-model="realName"
            :placeholder="t('auth.plname')"
            v-if="!hasauthen || revalidation"
          />
          <view v-else>{{ realName }}</view>
        </view>
        <view class="name">{{ t("auth.card") }}</view>
        <view class="item-input">
          <input
            v-if="!hasauthen || revalidation"
            type="text"
            v-model="cardNo"
            :placeholder="t('auth.plcard')"
          />
          <view v-else>{{ cardNo }}</view>
        </view>
        <view v-if="hasauthen">
          <view class="name">{{ t("auth.status") }}</view>
          <view class="item-input">
            <view>
              <text v-if="status == 0">{{ t("auth.checking") }}</text>
              <text v-if="status == 1">{{ t("auth.succe") }}</text>
              <text v-if="status == 2">{{ t("auth.fail") }}</text>
            </view>
          </view>
        </view>
		 <view class="name">{{ t("withdraw.notes") }}</view>
		<view class="item-input" v-if="revalidation">
		  {{noets}}
		</view>
      </view>

      <view class="operation" v-if="!hasauthen || revalidation">
        <button @click="confirm">{{ t("auth.cm") }}</button>
      </view>
    </view>
  </view>
</template>
<script setup>
import { ref, onMounted, toRaw, nextTick, computed, watch } from "vue";
import Navbar from "../../components/Navbar.vue";
import config from "../../networks/config";
// import request from "../../networks/request";
import api from "../../networks/apis";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const realName = ref("");
const status = ref(1); //认证状态
const cardNo = ref("");
const email = ref("");
const verfyCode = ref("");
const send = ref(false);
// 传参用
const cardImgFront = ref(""); //身份证正面
const cardImgBack = ref(""); //身份证反面
//展示用
const cardImgFront1 = ref(""); //身份证正面
const cardImgBack1 = ref(""); //身份证反面
const hasauthen = ref(false); //是否已认证
const revalidation = ref(false); //是否需要重新认证
const noets = ref(''); //是否需要重新认证
const is_upload = ref(0); //是否

onMounted(async () => {
  const { data } = await api.getDocumentInfoApi();
  const { info } = data;
  cardImgFront1.value = info.front_pic;
  cardImgBack1.value = info.opposite_pic;
  realName.value = info.name;
  cardNo.value = info.number;
  status.value = info.status;
  hasauthen.value = data.is_ok;
  revalidation.value = data.info.status == 2
  noets.value = data.info.notes
  is_upload.value = data.info.status
});
// 上传图片
const upload = async (type) => {
  if (hasauthen.value && !revalidation) {
    return;
  }
  const url = config.BASE_DOMAIN + "/api/authentication/upload";
  uni.showLoading({
    mask: true,
  });
  uni.chooseImage({
    count: 1, //默认9
    sizeType: ["compressed"], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ["album", "camera"], //从相册选择
    success: (res) => {
      //用箭头函数，this指向上下文
      uni.uploadFile({
        url: url,
        filePath: res.tempFilePaths[0],
        name: "photo",
        header: {
          // 在这里可以设置其他请求头
          Authorization: "Bearer " + localStorage.getItem("token") || "",
        },
        success: (uploadFileRes) => {
          console.log("uploadFileRes", JSON.parse(uploadFileRes.data).data);
          const data = JSON.parse(uploadFileRes.data).data;
          if (type == 1) {
            cardImgFront.value = data.path || "";
            cardImgFront1.value = data.view_path || "";
          } else {
            cardImgBack.value = data.path || "";
            cardImgBack1.value = data.view_path || "";
          }
        },
        complete: () => {
          uni.hideLoading();
        },
      });
    },
    fail: (err) => {
      console.log("上传失败", err);
      uni.hideLoading();
    },
  });
  const t = setTimeout(() => {
    console.log("关闭loading");
    clearTimeout(t);
    uni.hideLoading();
  }, 3000);
};
// 验证码
const sendCode = () => {
  if (send.value) {
    return;
  }
  sendEmailCode();
};
// const bindEmail = async () => {
//   if (!verfyCode.value) {
//     uni.showToast({
//       title: "请输入邮箱验证码",
//       icon: "none",
//     });
//     return;
//   }
//   const res = await api.bindEmailApi({
//     email: email.value,
//     code: verfyCode.value,
//   });
//   if (res.code != 200) {
//     uni.showToast({
//       title: res.msg || res.data.msg || "绑定邮箱失败",
//       icon: "error",
//     });
//   } else {
//     uni.showToast({
//       title: "绑定邮箱成功",
//       icon: "success",
//     });
//   }
// };
const sendEmailCode = async () => {
  const reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
  if (!reg.test(email.value)) {
    uni.showToast({
      title: "Enter email",
      icon: "none",
    });
    return;
  }
  const res1 = await api.getEmailCodeApi({
    email: email.value,
  });
  if (res1.code != 0) {
    send.value = false;
    uni.showToast({
      title: "error",
      icon: "none",
    });
  } else {
    send.value = true;
    uni.showToast({
      title: "success",
      icon: "none",
    });
  }
};
// 提交
const confirm = async () => {
  uni.showLoading({
    title: "Loading",
    mask: true,
  });
  const reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
  if (!cardImgFront.value) {
    uni.showToast({
      title: "Enter Front of certificate",
      icon: "none",
    });
    return;
  }
  if (!cardImgBack.value) {
    uni.showToast({
      title: "Enter Back of certificate",
      icon: "none",
    });
    return;
  }
  
  if(!revalidation.value){
	 if (!reg.test(email.value)) {
	   uni.showToast({
	     title: "Enter email",
	     icon: "none",
	   });
	   return;
	 }
	 if (!verfyCode.value) {
	   uni.showToast({
	     title: "Enter email code",
	     icon: "none",
	   });
	   return;
	 } 
  }
  

  
  if (!realName.value) {
    uni.showToast({
      title: "Enter name",
      icon: "none",
    });
    return;
  }
  if (!cardNo.value) {
    uni.showToast({
      title: "Enter certificate",
      icon: "none",
    });
    return;
  }
   let res
  if(revalidation.value){
	  res = await api.updateUserDocument({
	     front_pic: cardImgFront.value,
	     opposite_pic: cardImgBack.value,
	     name: realName.value,
	     number: cardNo.value,
	     email: email.value,
	     code: verfyCode.value,
	   }); 
  }else{
	res = await api.authenticationApi({
	   front_pic: cardImgFront.value,
	   opposite_pic: cardImgBack.value,
	   name: realName.value,
	   number: cardNo.value,
	   email: email.value,
	   code: verfyCode.value,
	 }); 
  }
  

  if (res.code != 0) {
    uni.hideLoading();
    uni.showToast({
      title: res.msg || res.data.msg || "error",
      icon: "error",
    });
  } else {
    uni.hideLoading();
    uni.showToast({
      title: "success",
      icon: "success",
      duration: 1000,
    });
    const t = setTimeout(() => {
      clearTimeout(t);
      uni.reLaunch({
        url: "/pages/my/index",
      });
    }, 1500);
  }
};
</script>
<style lang="scss" scoped>
.authentication {
  width: 750rpx;
  min-height: 100vh;
  padding-bottom: 85rpx;
  background: linear-gradient(180deg, #040a40 0%, #042e40 0%, #0d1324 100%);
  color: #fff;
}
.container {
  padding: 0 30rpx;
  margin-top: 30rpx;
}
.content {
  width: 100%;
  height: 406rpx;
  background-color: #000;
  padding: 36rpx 28rpx;
  border-radius: 12rpx;
  margin-top: 25rpx;
  .upload {
    width: 100%;
    height: 242rpx;
    border: 1rpx dashed #666;
    .upload-img {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .title {
    width: 100%;
    margin-top: 25rpx;
    .text1 {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28rpx;
    }
    .text2 {
      width: 100%;
      margin-top: 15rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 24rpx;
      color: #4f575b;
    }
  }
}
.content2 {
  width: 100%;
  margin-top: 25rpx;
  .title {
    margin: 25rpx 0;
  }
  .name {
    margin: 25rpx 0;
  }
  .item-input {
    width: 100%;
    height: 89rpx;
    background-color: #000;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    padding-left: 15rpx;
  }
  .email {
    margin-top: 25rpx;
    display: flex;
    align-items: center;
    .email-input {
      height: 89rpx;
      background-color: #000;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-self: center;
      padding-left: 15rpx;
    }
    .code-btn {
      width: 255rpx;
      height: 78rpx;
      margin-left: 25rpx;
      line-height: 78rpx;
      font-size: 26rpx;
      font-weight: 600;
      background: linear-gradient(133deg, #91e3d7 0%, #2b9bb2 100%);
    }
  }
}
.operation {
  margin-top: 75rpx;
  button {
    height: 89rpx;
    line-height: 89rpx;
    background: linear-gradient(133deg, #91e3d7 0%, #2b9bb2 100%);
    border-radius: 20rpx;
    font-size: 33rpx;
    font-weight: 600;
  }
}
</style>
